package com.curso.lab1.dao.impl;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.hibernate.Query;
import org.hibernate.Session;

import com.curso.lab1.dao.intf.PhoneDAO;
import com.curso.lab1.model.Phone;
import com.curso.lab1.model.User;

public class PhoneDAOImpl implements PhoneDAO {

	private Session session;
	
	public PhoneDAOImpl(Session session) {
		this.session = session;
	}
	
	@SuppressWarnings("unchecked")
	public List<Phone> getAll() {
		Query query = session.createQuery("from Phone");
		return (List<Phone>)query.list();
	}

	public Phone get(Long id) {
		return (Phone)session.get(Phone.class, id);
	}

	public boolean exists(Long id) {
		Phone phone = get(id);
		return phone != null;
	}

	public Phone save(Phone phone) {
		session.save(phone);
		return phone;
	}

	public void delete(Long id) {
		Query query = session.createSQLQuery("delete from phones where id = :id");
		query.setParameter("id", id);
		query.executeUpdate();
	}

	public List<Phone> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
		Query query = session.getNamedQuery(queryName);
		if (queryParams != null) {
			for (Entry<String, Object> element : queryParams.entrySet()) {
				query.setParameter(element.getKey(), element.getValue());
			}
		}
        return query.list();
	}

	@SuppressWarnings("unchecked")
	public List<Phone> getAllPhones(User user) {
		Query query = session.createQuery("from Phone where User.phones = :userid");
		query.setParameter("userid", user.getId());
		return query.list();
	}

}
